<template>
  <t-modal
    :title="title"
    width="900px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="onSubmit()"
    wrapClassName="add-modal-container"
    v-bind="footer"
    forceRender
    :confirmLoading="submitLoading"
  >
    <div class="curve-modal-body">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="isDisabled"
      >
        <a-form-model-item label="文件编号" prop="fileCode">
          <a-input v-model="form.fileCode" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="名称" prop="fileName">
          <a-input v-model="form.fileName" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="发文时间" prop="publicationDay">
          <a-date-picker
            placeholder="请选择"
            style="width: 100%"
            v-model="form.publicationDay"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            :disabled="isDisabled"
          />
        </a-form-model-item>
        <a-form-model-item
          label="成果文件"
          prop="files"
          :rules="{
            required: true,
            message: '请选择成果文件',
          }"
        >
          <bjUploadFile
            :viewMode="isDisabled"
            :count="20"
            v-model="form.files"
            @preview="viewFile($event)"
            @download="downloadFile($event)"
            @change="handleUpLoadFile($event)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea placeholder="请输入" v-model="form.remark" :rows="4" />
        </a-form-model-item>
        <a-form-model-item label="提交人">
          <a-input v-model="form.creator" disabled />
        </a-form-model-item>
        <a-form-model-item label="提交时间">
          <a-input v-model="form.createTime" disabled />
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import { getNowDateStr } from "@/utils/util.js";
//附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
export default {
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: [String, Number],
      default: 1,
    },
    parameter: {
      type: Object,
      default() {
        return {};
      },
    },
    treeItem: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      title: "新增",
      footer: {},
      isDisabled: false,
      submitLoading: false,
      form: {
        //文件编号
        fileCode: "",
        //名称
        fileName: "",
        //发文时间
        publicationDay: "",
        //成果文件
        files: [],
        //备注
        remark: "",
        //提交人
        creator: "",
        //提交时间
        createTime: "",
      },
      rules: {
        fileCode: [
          {
            required: true,
            message: "请输入文件编号",
          },
        ],
        fileName: [
          {
            required: true,
            message: "请输入名称",
          },
        ],
        publicationDay: [
          {
            required: true,
            message: "请选择发文时间",
          },
        ],
      },
      //所属文件夹
      treeData: [],
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    ...mapGetters(["configData", "nickname"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },

  methods: {
    //查询数据
    async getData() {
      await this.filterTitle();
      //详情
      if (this.operateType != 1) {
        this.getDetail();
      } else {
        this.form.creator = this.nickname;
        this.form.createTime = getNowDateStr(2);
      }
    },

    //
    filterTitle() {
      let { operateType } = this;
      switch (operateType) {
        case 1:
          this.title = "新增";
          this.footer = {};
          this.isDisabled = false;
          break;

        case 2:
          this.title = "编辑";
          this.footer = {};
          this.isDisabled = false;
          break;

        case 3:
          this.title = "详情";
          this.footer = { footer: null };
          this.isDisabled = true;
          break;

        default:
          break;
      }
    },

    //上传附件
    handleUpLoadFile({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["files"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form["files"][index], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form["files"][index], "url", res.url);
          this.$set(this.form["files"][index], "creator", this.form.creator);
          this.$set(
            this.form["files"][index],
            "createTime",
            this.form.createTime
          );
        })
        .catch((_) => {
          this.$set(this.form["files"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["files"][index], "loading", false);
        });
    },

    //下载
    downloadFile(row) {
      let { url } = row;
      downloadDfs(url);
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { operateType } = this;
          //新增
          if (operateType == 1) {
            this.saveFormData();
          }
          //编辑
          if (operateType == 2) {
            this.updateFormData();
          }
        }
      });
    },

    //新增
    saveFormData() {
      let { form } = this;
      const fileList = form.files.map(
        ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
      );
      let formJson = {
        //文件编号
        fileCode: form.fileCode,
        //名称
        fileName: form.fileName,
        //发文时间
        publicationDay: form.publicationDay,
        //成果文件
        files: JSON.stringify(fileList),
        //备注
        remark: form.remark,
      };
      this.submitLoading = true;
      axios
        .post(`/probusiness/constructionPermit/saveOrUpdate`, formJson, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("处理成功", 1.5);
            this.$parent.getTableData();
            this.closeModal();
          } else {
            this.$message.error(res?.message ?? "处理失败");
          }
        })
        .catch((_) => {})
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //编辑
    updateFormData() {
      let { form } = this;
      const fileList = form.files.map(
        ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
      );
      let formJson = {
        //数据id
        uuid: form.uuid,
        //文件编号
        fileCode: form.fileCode,
        //名称
        fileName: form.fileName,
        //发文时间
        publicationDay: form.publicationDay,
        //成果文件
        files: JSON.stringify(fileList),
        //备注
        remark: form.remark,
      };
      this.submitLoading = true;
      axios
        .post(`/probusiness/constructionPermit/saveOrUpdate`, formJson, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("处理成功", 1.5);
            this.$parent.getTableData();
            this.closeModal();
          } else {
            this.$message.error(res?.message ?? "处理失败");
          }
        })
        .catch((_) => {})
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //详情
    getDetail() {
      let { uuid } = this.parameter;
      axios
        .post(
          `/probusiness/constructionPermit/getDetail?varchar=${uuid}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.form = {
            //数据id
            uuid: res?.uuid,
            //文件编号
            fileCode: res?.fileCode,
            //名称
            fileName: res?.fileName,
            //发文时间
            publicationDay: res?.publicationDay,
            //成果文件
            files: JSON.parse(res?.files ?? "[]"),
            //备注
            remark: res?.remark,
            //提交人
            creator: res.creator,
            //提交时间
            createTime: res.createTime,
          };
        })
        .catch((_) => {});
    },

    //重置表单
    resetForm() {
      this.form = {
        //文件编号
        fileCode: "",
        //名称
        fileName: "",
        //发文时间
        publicationDay: "",
        //成果文件
        files: [],
        //备注
        remark: "",
        //提交人
        creator: "",
        //提交时间
        createTime: "",
      };
      this.$refs.ruleForm.resetFields();
    },

    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
    .curve-modal-body {
      box-sizing: border-box;
      padding: 14px 70px 14px 40px;
      max-height: 700px;
      overflow: auto;
      .ant-form-item {
        display: flex;
        .ant-form-item-label {
          flex-shrink: 0;
          width: 140px;
          label {
            color: #333333;
          }
        }
        .ant-form-item-control-wrapper {
          flex: 1;
          overflow: hidden;
        }
      }
      .bj-upload-file {
        .choosed-file-warp {
          width: 100%;
        }
      }
    }
  }
}
</style>
